package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"

	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/server/web"
)

// MemberTransactionController 处理会员交易记录相关请求
type MemberTransactionController struct {
	web.Controller
}

// List 获取会员交易记录列表
func (c *MemberTransactionController) List() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 解析过滤条件
	filters := make(map[string]interface{})

	// 会员ID
	if memberId, err := c.GetInt64("member_id", 0); err == nil && memberId > 0 {
		filters["member_id"] = memberId
	}

	// 交易类型
	if transactionType, err := c.GetInt8("type", -1); err == nil && transactionType != -1 {
		filters["type"] = transactionType
	}

	// 支付渠道
	if paymentChannel := c.GetString("payment_channel"); paymentChannel != "" {
		filters["payment_channel"] = paymentChannel
	}

	// 交易状态
	if status, err := c.GetInt8("status", -1); err == nil && status != -1 {
		filters["status"] = status
	}

	// 交易流水号
	if transactionNo := c.GetString("transaction_no"); transactionNo != "" {
		filters["transaction_no"] = transactionNo
	}

	// 订单号
	if orderNo := c.GetString("order_no"); orderNo != "" {
		filters["order_no"] = orderNo
	}

	// 时间范围
	if startTime, err := c.GetInt64("start_time", 0); err == nil && startTime > 0 {
		filters["start_time"] = startTime
	}

	if endTime, err := c.GetInt64("end_time", 0); err == nil && endTime > 0 {
		filters["end_time"] = endTime
	}

	// 加盟商权限过滤 - 非总部管理员只能查看自己加盟商的交易记录
	if admin.FranchiseId > 0 {
		filters["franchise_id"] = admin.FranchiseId
	}

	// 获取交易记录列表
	transactions, total, err := models.GetTransactionList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取交易记录列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回交易记录列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取交易记录列表成功",
		"data": map[string]interface{}{
			"list":  transactions,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// Detail 获取交易记录详情
func (c *MemberTransactionController) Detail() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取记录ID
	id, err := c.GetInt64("id")
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的记录ID",
		}
		c.ServeJSON()
		return
	}

	// 获取交易记录详情，带加盟商权限验证
	transaction, err := models.GetTransactionById(id, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取交易记录详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取关联会员信息
	member, err := models.GetMemberById(transaction.MemberId, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回交易记录详情
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取交易记录详情成功",
		"data": map[string]interface{}{
			"transaction": transaction,
			"member":      member,
		},
	}
	c.ServeJSON()
}

// GetByTransactionNo 根据交易流水号获取交易记录
func (c *MemberTransactionController) GetByTransactionNo() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取交易流水号
	transactionNo := c.GetString("transaction_no")
	if transactionNo == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "交易流水号不能为空",
		}
		c.ServeJSON()
		return
	}

	// 获取交易记录
	transaction, err := models.GetTransactionByTransactionNo(transactionNo)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取交易记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 加盟商权限验证
	if admin.FranchiseId > 0 {
		// 验证会员是否属于该加盟商
		member, err := models.GetMemberById(transaction.MemberId, admin.FranchiseId)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权访问该交易记录",
			}
			c.ServeJSON()
			return
		}

		if member.FranchiseId != admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权访问该交易记录",
			}
			c.ServeJSON()
			return
		}
	}

	// 返回交易记录
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取交易记录成功",
		"data":    transaction,
	}
	c.ServeJSON()
}

// Stats 获取交易统计信息
func (c *MemberTransactionController) Stats() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析时间范围
	startTime, err := c.GetInt64("start_time", 0)
	if err != nil || startTime <= 0 {
		// 默认为今天开始时间
		today := time.Now()
		startTime = time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, time.Local).Unix()
	}

	endTime, err := c.GetInt64("end_time", 0)
	if err != nil || endTime <= 0 {
		// 默认为当前时间
		endTime = time.Now().Unix()
	}

	// 计算各种统计数据，需要加盟商权限过滤
	o := orm.NewOrm()

	// 统计交易总额、交易笔数、成功率等
	var totalAmount float64
	var totalCount int64
	var successCount int64
	var failedCount int64
	var processingCount int64
	var recentTransactions []*models.Transaction

	// 交易类型统计
	var paymentCount int64
	var refundCount int64
	var rechargeCount int64
	var withdrawCount int64

	// 支付渠道统计
	var alipayAmount float64
	var wechatAmount float64
	var balanceAmount float64
	var otherAmount float64

	// 加盟商权限过滤条件
	var memberQuery string
	var memberParams []interface{}
	var memberIds orm.ParamsList

	if admin.FranchiseId > 0 {
		// 获取该加盟商下的所有会员ID
		_, err := o.QueryTable(new(models.Member)).
			Filter("franchise_id", admin.FranchiseId).
			Filter("is_deleted", 0).
			ValuesFlat(&memberIds, "id")
		if err != nil || len(memberIds) == 0 {
			// 没有会员，返回空数据
			c.Data["json"] = map[string]interface{}{
				"success": true,
				"message": "获取交易统计信息成功",
				"data": map[string]interface{}{
					"total_amount":        0,
					"total_count":         0,
					"success_count":       0,
					"success_rate":        0,
					"payment_count":       0,
					"refund_count":        0,
					"recharge_count":      0,
					"withdraw_count":      0,
					"alipay_amount":       0,
					"wechat_amount":       0,
					"balance_amount":      0,
					"other_amount":        0,
					"recent_transactions": []interface{}{},
				},
			}
			c.ServeJSON()
			return
		}

		// 构建IN查询
		memberQuery = "member_id IN (?)"
		memberParams = []interface{}{memberIds}
	} else {
		memberQuery = "1=1"
		memberParams = []interface{}{}
	}

	// 交易总额和笔数统计
	countSQL := fmt.Sprintf(`
		SELECT 
			COUNT(*) as total_count,
			SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as success_count,
			SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as failed_count,
			SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as processing_count,
			SUM(amount) as total_amount
		FROM ss_transaction 
		WHERE %s AND is_deleted = 0 AND created_at BETWEEN ? AND ?
	`, memberQuery)

	err = o.Raw(countSQL, append(memberParams, startTime, endTime)...).QueryRow(
		&totalCount, &successCount, &failedCount, &processingCount, &totalAmount,
	)

	// 交易类型统计
	typeSQL := fmt.Sprintf(`
		SELECT 
			SUM(CASE WHEN type = 1 THEN 1 ELSE 0 END) as payment_count,
			SUM(CASE WHEN type = 2 THEN 1 ELSE 0 END) as refund_count,
			SUM(CASE WHEN type = 3 THEN 1 ELSE 0 END) as recharge_count,
			SUM(CASE WHEN type = 4 THEN 1 ELSE 0 END) as withdraw_count
		FROM ss_transaction 
		WHERE %s AND is_deleted = 0 AND status = 1 AND created_at BETWEEN ? AND ?
	`, memberQuery)

	err = o.Raw(typeSQL, append(memberParams, startTime, endTime)...).QueryRow(
		&paymentCount, &refundCount, &rechargeCount, &withdrawCount,
	)

	// 支付渠道统计
	channelSQL := fmt.Sprintf(`
		SELECT 
			SUM(CASE WHEN payment_channel = 'alipay' THEN amount ELSE 0 END) as alipay_amount,
			SUM(CASE WHEN payment_channel = 'wechat' THEN amount ELSE 0 END) as wechat_amount,
			SUM(CASE WHEN payment_channel = 'balance' THEN amount ELSE 0 END) as balance_amount,
			SUM(CASE WHEN payment_channel NOT IN ('alipay', 'wechat', 'balance') THEN amount ELSE 0 END) as other_amount
		FROM ss_transaction 
		WHERE %s AND is_deleted = 0 AND status = 1 AND created_at BETWEEN ? AND ?
	`, memberQuery)

	err = o.Raw(channelSQL, append(memberParams, startTime, endTime)...).QueryRow(
		&alipayAmount, &wechatAmount, &balanceAmount, &otherAmount,
	)

	// 获取最近的交易记录
	qs := o.QueryTable(new(models.Transaction)).Filter("is_deleted", 0)

	if admin.FranchiseId > 0 {
		// 加盟商权限过滤
		qs = qs.FilterRaw("member_id", fmt.Sprintf("member_id IN (%s)", memberIdsToString(memberIds)))
	}

	qs = qs.Filter("created_at__gte", startTime).Filter("created_at__lte", endTime)
	qs.OrderBy("-created_at").Limit(10).All(&recentTransactions)

	// 计算成功率
	successRate := 0.0
	if totalCount > 0 {
		successRate = float64(successCount) / float64(totalCount) * 100
	}

	// 返回统计数据
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取交易统计信息成功",
		"data": map[string]interface{}{
			"total_amount":        totalAmount,
			"total_count":         totalCount,
			"success_count":       successCount,
			"failed_count":        failedCount,
			"processing_count":    processingCount,
			"success_rate":        successRate,
			"payment_count":       paymentCount,
			"refund_count":        refundCount,
			"recharge_count":      rechargeCount,
			"withdraw_count":      withdrawCount,
			"alipay_amount":       alipayAmount,
			"wechat_amount":       wechatAmount,
			"balance_amount":      balanceAmount,
			"other_amount":        otherAmount,
			"recent_transactions": recentTransactions,
			"start_time":          startTime,
			"end_time":            endTime,
		},
	}
	c.ServeJSON()
}

// 辅助函数，将会员ID列表转换为字符串
func memberIdsToString(ids orm.ParamsList) string {
	if len(ids) == 0 {
		return "0"
	}

	result := ""
	for i, id := range ids {
		if i > 0 {
			result += ","
		}
		result += fmt.Sprintf("%v", id)
	}
	return result
}
